/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.account.controller.admin;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Refunds;
import com.rzico.account.entity.Transfer;
import com.rzico.account.model.Attach;
import com.rzico.account.service.TransferService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.plugin.TransferPlugin;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysSequenceService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 付款单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "付款单接口")
@RestController
@RequestMapping("/admin/transfer")
public class TransferAdminController extends BaseController {

    @Autowired
    private TransferService transferService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    protected SysMchService sysMchService;

    @Autowired
    private SysSequenceService sysSequenceService;

    /**
     * 分页查询付款单
     *
     * @return
    */
    @ApiOperation("分页查询付款单")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "supplierId", value = "供应商Id", dataType = "Long", paramType = "query"),
    })
    public CommResult<Transfer> list(Date startDate, Date endDate,Long supplierId, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate", DateUtils.truncate(startDate, Calendar.DATE));
        }
        if (endDate!=null){
            params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        if (supplierId!=null){
            params.put("supplierId",supplierId);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getMchType().equals(3)) {
            //ISV
            if (enterprise!=null) {
                params.put("isvId", sysMch.getIsvId());
            } else {
                return CommResult.error("没有开通企业");
            }
        } else
        if (sysMch.getMchType().equals(2)) {
            //特约商户
            if (enterprise!=null) {
                params.put("enterpriseId", enterprise.getId());
            } else {
                return CommResult.error("没有开通企业");
            }
        } else {
            //特约商户
            if (enterprise!=null) {
                params.put("enterpriseId", enterprise.getId());
            } else {
                return CommResult.error("没有开通企业");
            }
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Transfer> list = transferService.selectList(params);
        PageResult<Transfer> pageResult = new PageResult<Transfer>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条付款单
     *
     * @return
    */
    @ApiOperation("查询单条付款单")
    @GetMapping("/find/{id}")
    public CommResult<Transfer> find(@PathVariable String id) {
        Transfer result = transferService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("transfer",result);
        return CommResult.success(result);

    }

    /**
     * 保存付款单
     *
     * @param list
     * @return
     */
    @ApiOperation("保存付款单")
    @PostMapping("/save")
    public CommResult<Transfer> save(@RequestBody List<Transfer> list) {
        logger.info(">>>>>>>>>>>>>>>>>>保存付款单 start<<<<<<<<<<<<<<<<<<<<");
        if (null == list || list.size() == 0){
            return CommResult.error("收款明细为空");
        }
        logger.info("保存付款单传参: [{}]", list.toString());
        String errMsg = "";
        for (Transfer transfer : list){
            if (null == transfer.getAmount() || transfer.getAmount().compareTo(BigDecimal.ZERO)==0){
                errMsg = "付款金额为空或者0";
                break;
            }
            if (StringUtils.isEmpty(transfer.getPaymentPluginId())){
                errMsg = "支付方式为空";
                break;
            }
            if (null == transfer.getSupplierId()){
                errMsg = "供应商为空";
                break;
            }
            if (null == transfer.getPayableId()){
                errMsg = "应付款ID为空";
                break;
            }
        }
        if (StringUtils.isNotEmpty(errMsg)){
            return CommResult.error(errMsg);
        }

        int affectCount = transferService.insert(list);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        return CommResult.success();

    }


    /**
     * 付款单确认
     *
     * @param id
     * @return
     */
    @ApiOperation("付款单确认")
    @PostMapping("/confirm/{id}")
    public CommResult<Transfer> confirm(@PathVariable Long id) {

        Assert.notNull(id, "付款单号为空");
        int affectCount = transferService.confirm(id);
        if (affectCount <= 0){
            return CommResult.error();
        }

        Transfer result = transferService.findById(id);
        return CommResult.success(result);

    }


    /**
     * 付款单取消
     *
     * @param id
     * @return
     */
    @ApiOperation("付款单取消")
    @PostMapping("/cancel/{id}")
    public CommResult<Transfer> cancel(@PathVariable Long id) {

        Assert.notNull(id, "付款单号为空");

        int affectCount = transferService.cancel(id);
        if (affectCount <= 0){
            return CommResult.error();
        }

        Transfer result = transferService.findById(id);
        return CommResult.success(result);

    }


    /**
     * 批量删除付款单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除付款单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除付款单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Transfer> del(@PathVariable String ids) {

        transferService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新付款单
     *
     * @param transfer
     * @return
     */
    @Log(desc = "更新付款单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新付款单")
    @PostMapping("/update")
    public CommResult<Transfer> update(@RequestBody Transfer transfer) {
        int affectCount = transferService.updateByPrimaryKeySelective(transfer);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Transfer result = transferService.findById(transfer.getId());
        return CommResult.success(result);
    }


    /**
     * 对账
     *
     * @param id
     * @return
     */
    @Log(desc = "对账", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("对账")
    @PostMapping("/query")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "付款单ID", dataType = "String", paramType = "query")
    })
    public CommResult<Transfer> query(Long id) {
        Transfer transfer = transferService.findById(id);
        if (transfer.getPaymentPluginId()==null) {
            return CommResult.error("没有付款");
        }

        TransferPlugin transferPlugin = sysPluginService.getTransferPlugin(transfer.getPaymentPluginId());

        Enterprise enterprise = enterpriseService.findById(transfer.getEnterpriseId());

        SysPlugin sysPlugin = sysPluginService.findByPlugin(enterprise.getMchId(),transfer.getPaymentPluginId());
        if (sysPlugin==null) {
            return CommResult.error("无效插件编号");
        }
        Map<String,Object> resultMap = transferPlugin.query(sysPlugin,transfer.getSn(),null);

        if ("0000".equals(resultMap.get("return_code").toString())) {
            try {
                transferService.handle(transfer.getSn(),resultMap.get("tranSn").toString());
                return CommResult.success(transfer);
            } catch (Exception e) {
                return CommResult.error("付款通知失败");
            }
        } else {
            if (!"0001".equals(resultMap.get("return_code").toString())) {
                transfer.setTranSn(resultMap.get("error_msg").toString());
                transfer.setStatus(3);
                transferService.updateByPrimaryKeySelective(transfer);
            }
            return CommResult.error(resultMap.get("err_msg").toString());
        }

    }

    /**
     *
     * 发起付款
     *
     * @param id
     * @return
     */
    @Log(desc = "发起付款", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("发起付款")
    @PostMapping("/submit")
    @ApiImplicitParams(
    {@ApiImplicitParam(name = "id", value = "付款单ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "paymentPluginId", value = "付款方式(1:自动打款,2:人工打款)", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "tranSn", value = "付款凭证", dataType = "String", paramType = "query")
    })
    public CommResult<Transfer> submit(Long id,Integer paymentPluginId,String tranSn) {
        Transfer transfer = transferService.findById(id);
        if (transfer.getPaymentPluginId()==null) {
            return CommResult.error("没有付款");
        }

       if (transfer.getStatus().equals(2)) {
            return CommResult.error("不能重复付款");
       }

       if (transfer.getStatus().equals(1)) {
           return CommResult.error("不能重复付款");
       }

        if (paymentPluginId.equals(2)) {
            transfer.setPaymentPluginId("transferPluginId");
            transfer.setPaymentPluginName("人工打款");
            transferService.updateByPrimaryKeySelective(transfer);
            try {
                transferService.handle(transfer.getSn(),tranSn);
                return CommResult.success(transfer);
            } catch (Exception e) {
                return CommResult.error("付款通知失败");
            }
        } else {
            try {
                transferService.submit(transfer,"weixinWalletPlugin");
                return CommResult.success(transfer);
            } catch (Exception e) {
                return CommResult.error("付款通知失败");
            }
        }

    }


}
